/*
 * Copyright (C) 2009  Sylvain Maucourt (smaucourt@gmail.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 *
 */
package net.sylvek.where.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import net.sylvek.where.client.AdminService;
import net.sylvek.where.client.User;
import net.sylvek.where.entity.PMF;
import net.sylvek.where.entity.UserEntity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class AdminServiceImpl extends RemoteServiceServlet implements AdminService {

    @SuppressWarnings("unchecked")
    public List<User> getUsers()
    {
        List<User> result = new ArrayList<User>();
        PersistenceManager pm = PMF.get().getPersistenceManager();

        try {
            Query q = pm.newQuery(UserEntity.class);
            q.setRange(0, 500);
            q.setOrdering("update desc");
            Collection<UserEntity> r = (Collection<UserEntity>) q.execute();
            Iterator<UserEntity> i = r.iterator();
            while (i.hasNext()) {
                UserEntity u = i.next();
                result.add(new User(u.getName(), u.getUid(), u.getUpdate(), u.getIp(), u.getLocationHash()));
            }
        } finally {
            pm.close();
        }
        return result;
    }

    public boolean delete(String uid)
    {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            UserEntity user = pm.getObjectById(UserEntity.class, uid);
            pm.deletePersistent(user);
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            pm.close();
        }
    }
}
